package com.tju.t5.interceptor;

import java.util.Dictionary;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.tju.t5.entity.Role;
import com.tju.t5.entity.Privilege;

public class AcessControlInterceptor extends AbstractInterceptor {
	
	private Dictionary<String, String> accessDict = null;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public AcessControlInterceptor()
	{
		/*
		 * Construct Access Control List
		 */
		
		accessDict.put("userManage", "userManage");
		accessDict.put("roleManage", "roleManage");
		accessDict.put("flightSearch", "flightSearch");
		accessDict.put("flightManage", "flightManage");
		accessDict.put("facilityManage", "facilityManage");
		accessDict.put("newsSearch", "newsSearch");
		accessDict.put("newsSubscribe", "newssubscribe");
		accessDict.put("newsPublish", "newsPublish");
		accessDict.put("default", "default");
	}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		ActionContext context = invocation.getInvocationContext();
		String actionName = context.getName();
		String access = getAccessString(actionName);
		
		Map<String, Object> session = context.getSession();
		
		Role userRole = (Role) session.get("role");
		if(userRole != null)
		{
			// Check if the user has the access to the module
		}
		
		return null;
	}
	
	private String getAccessString(String path)
	{
		Pattern pattern = Pattern.compile("^[a-zA-Z]+_.*(.action)$");
		Matcher match = pattern.matcher(path);
		if(match.matches())
		{
			String actionModule = path.substring(0, path.indexOf("_"));
			return accessDict.get(actionModule);
		}
		else
		{
			return accessDict.get("default");
		}
	}

}
